﻿using System.Collections.Generic;

namespace PageAdmin.Utils
{
    /// <summary>
    /// 配置文件继承的基类
    /// </summary>
    public abstract class ConfigModelBase<T> where T : class, new()
    {
        private static T _TModel;
        static ConfigModelBase()
        {
            RemoveCache();
        }
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <returns></returns>
        public static T Get()
        {
            return _TModel;
        }

        /// <summary>
        /// 刷新配置文件
        /// </summary>
        private static void RemoveCache()
        {
            //自读取特性配置
            string configPath = ConfigFileAttributeHelper.GetConfigPath<T>();
            _TModel = XmlHelper.AllNodeValue<T>("configuration",configPath);
        }

        /// <summary>
        /// 通过实体更新配置文件,同步更新缓存
        /// </summary>
        public static void UpdateFile(T configModel)
        {
            //自读取特性配置
            string configPath = ConfigFileAttributeHelper.GetConfigPath<T>();
            string jsonResult = JsonHelper.JsonParse(configModel);
            Dictionary<string, string> dicConfig = JsonHelper.DeserializeObject<Dictionary<string, string>>(jsonResult);
            XmlHelper.UpdateNodeValue("configuration",dicConfig, configPath);
            RemoveCache();
        }

        /// <summary>
        /// 通过字典更新配置文件,同步更新缓存
        /// </summary>
        public static void UpdateFile(Dictionary<string, string> dicConfig)
        {
            //自读取特性配置
            string configPath = ConfigFileAttributeHelper.GetConfigPath<T>();
            XmlHelper.UpdateNodeValue("configuration", dicConfig, configPath);
            RemoveCache();
        }
    }
}
